<template>
	<div class="home" ref="homeScollTop" id="home">
		<!-- 关闭遮罩层按钮 -->
		<el-button type="warning" icon="el-icon-close" class="lz-close-fiexd" circle v-if="close.show" @click="closeMarks"></el-button>
		<el-card class="box-card" v-if="seal.UUID">
			<div slot="header" class="clearfix" style="display: flex;">
				<div>
					<span>UUID:<el-tag :size="size" :type="computeTagType(seal.UUID)">{{seal.UUID}}</el-tag></span>
				</div>
			</div>
			<div class="center">
				<sealTable :sealData="seal.data"></sealTable>
			</div>
		</el-card>
		<el-timeline class="el-timeline">
			<template v-for="(item,index) in testList">
				<el-timeline-item :timestamp="item.name" placement="top" v-for="(item2,index2) in item.commands" :key="item2.CommondNo" :id="item2.CommondNo">
					<el-card class="line-card">
						<div class="card-warp">
							<div class="card-title">{{item2.CommondName}}：</div>
							<div class="btn">
								<div  v-if="item2.isSuccess==0||item2.isSuccess==-1||item2.isSuccess==1">
									<el-button v-if="item2.isSuccess==0" :size="size" type="success">成功</el-button>
									<el-button v-if="item2.isSuccess==-1" :size="size" type="danger">失败</el-button>
									<el-button v-if="item2.isSuccess==1" :size="size" type="warning">跳过</el-button>
								</div>
								<div v-else>
									<el-button v-if="item2.CommondNo==testList[ativeTestNum].commands[commandIndex].CommondNo" :size="size" icon="el-icon-warning-outline" type="warning"
									 @click="skipNow()">{{'正在测试（'+time.num+'s后跳过）'}}</el-button>
									 <el-button v-else :size="size" icon="el-icon-loading">等待结果</el-button>
								</div>
							</div>
							<div v-if="item2.CommondNo==3" class="left">
								<el-image :src="picture.src" class="el-image">
									<div slot="error" class="image-slot">
										<i class="el-icon-picture-outline"></i>
									</div>
								</el-image>
							</div>
							<div v-if="item2.CommondNo==11" class="flex">
								<el-checkbox-group v-model="KeyTest.checkList">
									<el-checkbox :label="item.id" v-for="(item,index) in KeyTest.data" :key="item.id">{{item.lable}}</el-checkbox>
								</el-checkbox-group>
								<span class="tip">(请按指示点击印章上按键)</span>
							</div>
							
							<div v-if="item2.CommondNo==22&&read.ROM" class="flex-center">
								<el-button type="info" :size="size">读取：{{read.ROM}}</el-button>
								<el-button type="info" :size="size">配置：{{appVersionList.ROM}}</el-button>
							</div>
							<div v-if="item2.CommondNo==23&&read.APP" class="flex-center">
								<el-button type="info" :size="size">读取：{{read.APP}}</el-button>
								<el-button type="info" :size="size">配置：{{appVersionList.APP}}</el-button>
							</div>
							<div v-if="item2.CommondNo==36&&read.LET_signal" class="flex-center">
								<el-button type="info" :size="size">读取：{{read.LET_signal}}</el-button>
								<el-button type="info" :size="size">配置：{{AppConfig.appVersionList.LTELimit[0]}}与{{AppConfig.appVersionList.LTELimit[1]}}之间</el-button>
							</div>
							<div v-if="item2.CommondNo==24&&read.WIFI_MAC" class="flex-center">
								<el-button type="info" :size="size">{{read.WIFI_MAC}}</el-button>
							</div>
							<div v-if="item2.CommondNo==26&&read.IMEI" class="flex-center">
								<el-button type="info" :size="size">{{read.IMEI}}</el-button>
							</div>
							<div v-if="item2.CommondNo==27&&read.WIFI_BT" class="flex-center">
								<div v-for="(item,index) in read.WIFI_BT" :key="index">
									<el-button type="info" :size="size">SSID:{{item.SSID}}</el-button>
								</div>
							</div>
							<div v-if="item2.CommondNo==28&&read.Q_Electric" class="flex-center">
								<el-button type="info" :size="size">{{computeQ_Electric(read.Q_Electric)}}</el-button>
							</div>
							<div v-if="item2.CommondNo==33&&read.codeScanning" class="flex-center">
								<el-button type="info" :size="size">{{read.codeScanning}}</el-button>
							</div>
							<div v-if="item2.CommondNo==35&&read.Aging_state" class="flex-center">
								<el-button type="info" :size="size">{{read.Aging_state==0?'已老化':'未老化'}}</el-button>
							</div>
							
							<div v-if="item2.CommondNo==37&&read.ICCID" class="flex-center">
								<el-button type="info" :size="size">{{read.ICCID}}</el-button>
							</div>
							<div v-if="item2.CommondNo==39&&read.IMEI" class="flex-center">
								<el-input v-focus v-model="scan.IMEI" placeholder="请使用扫码枪扫码" :size="size" style="width: 200px;" @input="codeScanningChange"></el-input>
								<el-button type="info" :size="size">{{read.IMEI}}</el-button>
							</div>
							<div v-if="item2.CommondNo==40&&electricCurrent.value" class="flex-center">
								<el-button type="info" :size="size">读取：{{electricCurrent.value}}</el-button>
								<el-button type="info" :size="size">配置：{{appVersionList.electricCurrent}}</el-button>
							</div>
						</div>
					</el-card>
				</el-timeline-item>
			</template>
		</el-timeline>
		<image-viewer :z-index="8000" v-if="picture.showViewer" :on-close="closeViewer" :showIndex="picture.showIndex"
		 :url-list="[{fileUrl:picture.src}]" uuid="fileId" url="fileUrl" />
		<!-- 封装自动更新组件 -->
		<appUpdate></appUpdate>
		<!-- 二维码 -->
		<div class="lz-qrcode" v-if="QRcode.show" @click="QRcode.show=false">
			<div class="qrcodeWarp">
				<div class="qrcode" ref="qrCodeUrl"></div>
				<div class="text">{{QRcode.IMEI}}</div>
			</div>
		</div>
	</div>
</template>

<script>
	let that, workerProcess, message,loading,timer,receivedStr=""
	let SerialPort = require('serialport')
	import bus from "/static/js/bus.js";
	import imageViewer from '@/components/imageViewer/imageViewer'; //图片查看器
	import sealTable from '@/components/sealTable.vue';
	import appUpdate from '@/components/appUpdate/appUpdate.vue';
	import lzRowCol from '@/components/lzRowCol/lzRowCol.vue';
	import QRCode from 'qrcodejs2'
	import {
		mapGetters,
		mapActions
	} from 'vuex'
	import {
		log
	} from 'util';
	//网络通讯
	const net = require('net');
	//开启node子线程
	const {
		exec,
		spawn
	} = require('child_process');
	let path=require('path')
	import { ipcRenderer ,remote } from "electron";
	export default {
		computed: {
			...mapGetters(['size','appTypeEnd','appType','appTime','appMenuList','appVersionList','codeScanning','AppConfig']),
			computeQ_Electric(){
				return (data)=>{
					if(data=='1') {return '25%'}
					if(data=='2') {return '50%'}
					if(data=='3') {return '75%'}
					if(data=='4') {return '100%'}
				}
			},
			computeTagType(){
				return (uuid)=>{
					if(uuid==this.codeScanning) {
						return ''
					}else if(uuid!=this.codeScanning){
						return 'danger'
					}
				}
			}
		},
		components: {
			imageViewer,
			sealTable,
			appUpdate,
			lzRowCol
		},
		name: 'Home',
		directives: {
			// 注册一个局部的自定义指令 v-focus
			focus: {
			  // 指令的定义
			  inserted: function(el) {
				// 聚焦元素
				el.querySelector("input").focus();
			  }
			}
		},
		data() {
			return {
				QRcode:{//二维码
					show:false,
					IMEI:'',//IMEI值
				},
				close:{
					show:false
				},
				picture: {
					src: '', //当前检测的照片
					fileID:'',//云存储的id用于删除
					showViewer: false, //图片查看器
					showIndex: 0, //点击显示图片第几个
				},
				tcp: {
					client: null,
					HOST: "127.0.0.1",
					PORT: 12580,
				},
				ativeTestNum: 0, //当前检测项下标
				commandIndex: 0, //当前发送命令的下标
				testList: [], //检测项
				receivedStr: '', //接收的完整数据
				seal: {
					state: '', //当前设备连接状态
					UUID: '',
					data: [],//获取服务器印章的检测记录
				},
				// 按键测试
				KeyTest: {
					data: [{
						id: "1",
						lable: '开机'
					}, {
						id: "2",
						lable: '上键'
					}, {
						id: "3",
						lable: '下键'
					}, {
						id: "4",
						lable: '确认'
					}],
					checkList: []
				},
				read: {
					APP: '',
					ROM: '',
					WIFI_MAC: '',
					BT_MAC: '',
					IMEI: '',
					WIFI_BT: '',
					Q_Electric:'',//电量
					codeScanning:'',//扫码枪扫码
					Aging_state:'',//老化状态
					LET_signal:'',//4G强度
					ICCID:'',//ICCID
				},
				time:{
					num:60
				},
				popUp:{//当前弹出人为审核框信息
					active:'',//基本信息
					text:'',//标题
					show:false,
				},
				//扫码对比IMEI
				scan:{
					IMEI:'',
					result:null
				},
				//读取电流
				electricCurrent:{
					value:'',
					result:null
				}
			}
		},
		async mounted() {
			that = this
			// 初始化
			that.ledOpen('adb shell')
			bus.$off('menuMsseage')
			bus.$on('menuMsseage', (res) => {
				if (res.action == 'startTesting') { //开始检测
					that.initData() //初始化参数
					that.testList = JSON.parse(JSON.stringify(res.data))
					//开始检测功能项
					that.startTesting()
					//倒计时
					that.getCode()
					//设置扫码枪是否禁止输入
					that.setCodeScanningOnOff(true)
				}
				if (res.action == 'connectDevice') { //连接设备
					that.$lizhao.debounce(()=>{
						that.ledOpen('adb forward tcp:12580 tcp:10086')
					},1000)
				}
				if (res.action == 'sendCommand') { //发送指令
					that.ledOpen(res.data)
				}
				if(res.action=='signOutTest'){
					that.sendMsgToTcp('{"CommondNo":21,"CommondName": "结束产测模式","CommondParam": "","CommondTime":""}$')
				}
				if(res.action=='closeSocket'){
					that.sendMsgToTcp('{"CommondNo":888,"CommondName": "断开印章socket","CommondParam": "","CommondTime":""}$')
				}
				if(res.action=='preserveData'){//保存数据
					that.preserveData('all')
				}
				if(res.action=='resetData'){//重置数据
					//重置
					that.resetSeverData()
				}
				
			})
		},
		methods: {
			...mapActions('app',['setAppTypeEnd','setAppMenuList','setCodeScanningOnOff']),
			//串口通信读取电流
			serialPortFn(){
				console.log(that.AppConfig.serialPort.COM,that.AppConfig.serialPort.baudRate);
				let serialPort = new SerialPort(that.AppConfig.serialPort.COM, {
				    //波特率，可在设备管理器中对应端口的属性中查看
				    baudRate : that.AppConfig.serialPort.baudRate,
				    autoOpen:false
				})
				//连接串口后进行写入指令操作
				serialPort.open(function (err) {
				    if(serialPort.isOpen){
						console.log('打开串口成功');
						const buf1 = new Buffer(":MEAS:CURR?\r\n","utf8")
						serialPort.write(buf1, function (error, result) {
							console.log(error, result);
						})
				    }
				})
				//指令监听
				serialPort.on('data',function (data) {
					let electricCurrent=that.AppConfig.appVersionList.electricCurrent
					that.electricCurrent.value=data
				    console.log('监听的值： '+data+'配置的电流值：'+ electricCurrent);
					if(electricCurrent[0]<parseInt(data)<electricCurrent[1]){
						//处理结果是否人为审核
						that.humanAudit(that.electricCurrent.result)
					}else{
						that.isSuccessFn(-1, 'noPeople',that.electricCurrent.result.ExecResult)
					}
					
				})
				//错误监听
				serialPort.on('error',function (error) {
				    console.log('error: '+error)
				})
				//获取端口列表
				// SerialPort.list().then(
				//     ports => ports.forEach(console.log),
				//     err => console.error(err)
				// );
			},
			
			//扫码枪扫码对比imei
			codeScanningChange(){
				that.$lizhao.debounce(()=>{
					if(that.scan.IMEI!=that.read.IMEI){
						that.isSuccessFn(-1, 'noPeople',that.scan.result.ExecResult)
						return
					}
					if (that.scan.result.ExecResult) { //执行成功
						//处理结果是否人为审核
						that.humanAudit(that.scan.result)
					} else {
						//显示日志在子窗口
						that.showLogSubwindow('执行失败')
						//处理结果是否人为审核
						that.humanAudit(that.scan.result)
					}
				},500)
			},
			//检测目录
			async testingCatalogue(){
				console.log(that.seal.UUID);
				let dirPath=path.join(that.AppConfig.logDir,`/log/${that.$lizhao.getTime(0)}/${that.seal.UUID}`)
				//检测目录是否存在
				let onoff=await that.$lizhao.lzfs.stat(dirPath)
				if(!onoff){
					let arr= dirPath.split("\\")
					let str=''
					//循环创建目录
					for (var i = 0; i < arr.length-1; i++) {
						str+=arr[i]+'/'
						console.log(str,arr[i+1]);
						//创建目录
						let onoff=await that.$lizhao.lzfs.mkdir(path.join(str,arr[i+1]))
					}
				}
			},
			//创建二维码
			creatQrCode() {
				var qrcode = new QRCode(this.$refs.qrCodeUrl, {
					text: that.QRcode.IMEI, // 需要转换为二维码的内容
					width: 140,
					height: 140,
					colorDark: '#000000',
					colorLight: '#ffffff',
					correctLevel: QRCode.CorrectLevel.H
				})
			},
			//重置
			async resetSeverData(){
				let reqData={
					UUID:that.seal.UUID,
					active:'resetSeverData'
				}
				//先查询数据库当前工序是否检测过，检测过就更新数据
				let res=await that.GLOBAL.doPost('https://fc-mp-d469f3c9-30d2-4936-a92e-5888ccb3dd27.next.bspapp.com/http/AddSealData',reqData)
				if(res.code==0){
					that.$message.success('重置成功')
				}
			},
			//关闭遮罩层
			closeMarks(){
				loading&&loading.close();
				that.close.show=false
			},
			//跳过当前检测项
			skipNow(){
				that.isSuccessFn(1, 'skipNow')
				that.time.num=that.appTime
				//倒计时60秒
				that.getCode()
			},
			//倒计时60秒
			getCode() {
				this.time.num=that.appTime
				clearInterval(timer)
				timer= setInterval(() => {
					this.time.num--
					if (this.time.num === 0) {
						clearInterval(timer)
						that.skipNow()
					}
				}, 1000)
			},
			// 数据库查询
			async queryTest(str) {
				setTimeout(()=>{
					clearInterval(timer)
				},500)
				that.$confirm('检测项已全部检测完成，是否保存数据', '检测完毕', {
				  confirmButtonText: '保存',
				  cancelButtonText: '取消',
				  type: 'warning'
				}).then(() => {
					that.preserveData(str)
				}).catch(() => {
					bus.$emit('homeToMenu', {
						action: 'preserve',
						preserveDisabled: true
					})
				});
			},
			//查找当前设备数据并保存
			async preserveData(str){
				that.close.show=true
				loading = that.$loading({
				  lock: true,
				  text: '正在向安卓写入测试结果，稍等',
				  spinner: 'el-icon-loading',
				  background: 'rgba(0, 0, 0, 0.7)'
				});
				if (str == 'all') {
					//检测还有哪些项没有检测过true全部检测完成
					let endResult=that.isTested(that.testList)
					console.log('检测结果',endResult);
					//向远程数据库写入数据
					that.witerData(that.testList,endResult)
					
				}
			},
			//向远程数据库写入数据
			async witerData(req,onoff){
				let reqData={
					string:JSON.stringify(req),
					appType:that.appType,//当前检测的是哪道工序
					appTypeEnd:onoff,//是否全部检测合格true合格 false不合格
					UUID:that.seal.UUID,
					active:'addSealData'
				}
				//先查询数据库当前工序是否检测过，检测过就更新数据
				let res=await that.GLOBAL.doPost('https://fc-mp-d469f3c9-30d2-4936-a92e-5888ccb3dd27.next.bspapp.com/http/AddSealData',reqData)
				if(res.code==0){
					that.$message.success('存储成功')
					//关闭遮罩层
					that.closeMarks()
					//获取服务器印章里面的数据
					that.getSeverSealData()
					
				}
			},
			//关闭查看图片管理器
			closeViewer() {
				this.picture.showViewer = false
			},
			initData() {
				receivedStr = ''
				that.checkList = []
				that.testList = [] //每次执行之前清空列表
				that.ativeTestNum = 0 //当前检测项下标
				that.commandIndex = 0 //当前发送命令的下标
				that.KeyTest.checkList = []
				that.read = {
					APP: '',
					ROM: '',
					WIFI_MAC: '',
					BT_MAC: '',
					IMEI: '',
					WIFI_BT: '',
					Q_Electric :'',//电量
					codeScanning:'',//扫码枪扫码
					Aging_state:'',//老化状态
					LET_signal:'',//4G强度
					ICCID:'',//ICCID
				}
				//扫码对比IMEI
				that.scan={
					IMEI:'',
					result:null
				},
				//读取电流
				that.electricCurrent={
					value:'',
					result:null
				}
				that.topActiveInfo(false)
			},
			//显示弹框用户指定成功与否
			showOpen() {
				receivedStr = ''
				that.popUp.show=true
				return new Promise((result, reject) => {
					that.$confirm(that.popUp.text, '提示', {
						confirmButtonText: '成功',
						cancelButtonText: '失败',
						type: 'warning',
						showClose: false,
						closeOnClickModal: false,
						lockScroll: false
					}).then(() => {
						receivedStr = '' //每次执行下一项都要清空一下之前拼接结果
						//头部按钮信息显示关闭
						that.topActiveInfo(false)
						that.popUp.show=false
						result(0)
					}).catch(() => {
						receivedStr = '' //每次执行下一项都要清空一下之前拼接结果
						//头部按钮信息显示关闭
						that.topActiveInfo(false)
						that.popUp.show=false
						result(-1)
					});
				})
			},

			//开始检测功能项
			async startTesting() {
				let active =that.testList[that.ativeTestNum]
				//头部按钮信息显示
				that.topActiveInfo(true)
				let {
					isSuccess,
					popUp,
					...cmdData
				} = active.commands[that.commandIndex]
				cmdData.CommondTime = that.$lizhao.timeFormat(new Date, 'yyyy-mm-dd hh:MM:ss')
				//写入sn和对比sn
				if(cmdData.CommondNo==33||cmdData.CommondNo==38){
					if(!that.codeScanning||that.codeScanning.length!=24){//如果扫码枪值不存在或者长度不等于24位直接写入失败
						that.$nextTick(()=>{
							that.isSuccessFn(-1, 'noPeople',-1)
						})
						return
					}else{
						cmdData.CommondParam=that.codeScanning
					}
				}
				that.sendMsgToTcp(JSON.stringify(cmdData) + '$')
			},

			//当前执行命令是否成功
			isSuccessFn(onoff, type,resultData='') {
				let active = that.testList[that.ativeTestNum]
				console.log('当前指令',active.commands[that.commandIndex].CommondNo,that.ativeTestNum);
				//滚动到指定位置 behavior: 'smooth'
				document.getElementById(active.commands[that.commandIndex].CommondNo).scrollIntoView({ block: 'center', behavior: 'auto' })
				//显示日志在子窗口
				that.showLogSubwindow('当前指令是否成功'+active.commands[that.commandIndex].CommondNo+':'+onoff)
				//onoff: 0成功 -1失败  1跳过
				that.$set(active.commands[that.commandIndex],'isSuccess',onoff)
				that.$set(active.commands[that.commandIndex],'resultData',resultData)
				
				//判断当前检测项是否有多个指令检测
				if (active.commands.length - 1 > that.commandIndex) {
					that.commandIndex++
					//重启定时器
					that.getCode()
					//开始检测当前项的下一指令
					that.startTesting()
				} else {
					//判断是否有下一项检测
					if (that.testList.length - 1 > that.ativeTestNum) {
						that.ativeTestNum++
						that.commandIndex = 0
						//重启定时器
						that.getCode()
						//开始检测下一项的第一个指令
						that.startTesting()
					} else { //全部检测完毕
						console.log('全部检测完毕');
						that.ativeTestNum = 0
						that.commandIndex = 0
						clearInterval(timer)
						that.$message.success('全部检测完毕')
						that.topActiveInfo(false)
						that.queryTest('all')
						document.getElementById('home').scrollIntoView({ block: 'start', behavior: 'smooth' })
						//设置扫码枪是否禁止输入
						that.setCodeScanningOnOff(false)
					}
				}

			},
			//头部按钮信息显示
			topActiveInfo(show) {
				let data
				if (show) {
					let active = that.testList[that.ativeTestNum]
					console.log('正在执行第' + that.ativeTestNum + '项的---第' + that.commandIndex + '个指令');
					data = {
						action: 'btnInfo',
						data: {
							show: show,
							loading: true,
							text: `正在检测- -${active.name}- - ${active.commands[that.commandIndex].CommondName}`
						}
					}
				} else {
					let active = that.testList[that.ativeTestNum]
					data = {
						action: 'btnInfo',
						data: {
							show: show,
							loading: true,
							text: ''
						}
					}
				}
				//头部显示信息
				bus.$emit('topActiveInfo', data)
			},
			//发送指令
			ledOpen(str) {
				workerProcess = exec(str, {
					cwd: process.cwd() + '/cwd/adb'
				})
				// 打印正常的后台可执行程序输出
				workerProcess.stdout.on('data', function(data) {
					console.log('打印正常: ' + data.toString() + '-cmd:' + str)
					if (('--' + data).indexOf('shell@') > 0 && str == 'adb shell') {
						message && message.close()
						that.$message.success('程序已初始化，可点击连接')
					}
					//显示日志在子窗口
					that.showLogSubwindow('执行指令: ' + data.toString())
				})
				// 打印错误的后台可执行程序输出
				workerProcess.stderr.on('data', function(data) {
					console.log(data + '-cmd:' + str)
					if (('--' + data).indexOf('device/emulator') > 0 && !that.seal.state) {
						message = that.$message({
							iconClass: 'el-icon-loading',
							message: '发现端口被占用，正在清理端口，稍等',
							duration: 0,
						})
						that.ledOpen('adb kill-server')
						that.ledOpen('adb shell')
						return
					} else if (('--' + data).indexOf('devices/emulators') > 0) {
						//设置当前连接状态
						that.stateFn(false)
						that.$message.warning('未发现设备，请确保设备已进入调试模式')
						return
					} else if (('--' + data).indexOf('device offline') > 0) {
						that.$message.warning('设备不在线')
						return
					}
					//显示日志在子窗口
					that.showLogSubwindow('错误: ' + data.toString())
				})
				// 退出之后的输出
				workerProcess.on('close', function(code) {
					console.log('退出之后的输出：' + code + '-cmd:' + str)
					if (str == 'adb forward tcp:12580 tcp:10086' && code == 0) { //建立连接
						message && message.close()
						message = that.$message({
							iconClass: 'el-icon-loading',
							message: '正在初始化链接'
						})
						that.initTcp(that.tcp.PORT, that.tcp.HOST, true)
						
					}
					//显示日志在子窗口
					that.showLogSubwindow('退出')
				})
			},
			initTcp(PORT, HOST, show) {
				//初始化TCP连接
				this.tcp.client = new net.Socket();
				this.tcp.client.connect({
					port: PORT,
					host: HOST,
				}, () => {
					message.close()
					if (show) {
						that.$message.success('连接成功')
					}
					//显示日志在子窗口
					that.showLogSubwindow('连接成功'+ HOST + ":" + PORT)
					//获取当前设备uuid
					that.sendMsgToTcp('{"CommondNo":1,"CommondName": "获取当前设备uuid","CommondParam": "","CommondTime":""}$')
				});
				// 当接收到数据的时触发该事件。
				this.tcp.client.on("data", (data) => {
					console.log('当接收到数据的时触发该事件')
					if (data.toString().indexOf('$') < 0) {
						//没有$
						receivedStr += data.toString()
					} else {
						receivedStr += data.toString()
						//处理数据
						that.processingData(receivedStr)
						receivedStr=''
					}

				});
				// 一旦 socket 完全关闭就发出该事件, 监听连接关闭事件
				this.tcp.client.on("close", function() {
					console.log('一旦 socket 完全关闭就发出该事件')
					// 断开连接时初始化
					that.closeInit()
				});
			},
			// 断开连接时初始化
			closeInit() {
				message.close()
				that.$message.warning('连接失败，稍后重试')
				//设置扫码枪是否禁止输入
				that.setCodeScanningOnOff(false)
				//显示日志在子窗口
				that.showLogSubwindow('关闭连接')
				that.testList = []
				//设置当前连接状态
				that.stateFn(false)
				that.seal.UUID = ''
				that.topActiveInfo(false)
				
			},
			// 发送数据
			sendMsgToTcp(msg) {
				console.log(msg);
				//显示日志在子窗口
				that.showLogSubwindow('发送数据'+msg)
				this.tcp.client.write(msg);
			},
			//显示日志在子窗口
			showLogSubwindow(msg){
				//显示日志在子窗口
				ipcRenderer.send("new-setUp-window",{
					action:'drawLog',
					data:msg
				});
				that.writeLog(msg)
			},
			//向文件写入log
			writeLog(msg){
				if(that.seal.UUID){
					let pathUrl=path.join(that.AppConfig.logDir,`/log/${that.$lizhao.getTime(0)}/${that.seal.UUID}/${that.$lizhao.getTime(0)}.txt`)
					let msgDate=that.$lizhao.timeFormat(new Date().getTime(),'yyyy-mm-dd hh:MM:ss') + msg
					that.$lizhao.lzfs.appendFile(pathUrl,msgDate)
				}
			},
			// 手动关闭连接
			destroyTcp() {
				this.tcp.client.destroy();
			},
			//获取服务器印章里面的数据
			async getSeverSealData(){
				let reqData={
					appType:that.appType,//当前检测的是哪道工序
					UUID:that.seal.UUID,
					active:'seachSealData'
				}
				//先查询数据库当前工序是否检测过，检测过就更新数据
				let res=await that.GLOBAL.doPost('https://fc-mp-d469f3c9-30d2-4936-a92e-5888ccb3dd27.next.bspapp.com/http/AddSealData',reqData)
				if(res.code==0&&res.data&&res.data.data.length>0&&res.data.data[0].string){
					that.seal.data=JSON.parse(res.data.data[0].string)
					//处理服务器返回的印章检测数据
					that.workingProcedure(res.data.data[0])
					
				}else{
					//服务器当前没有存储此印章检测，需从头检测
					that.workingProcedure()
				}
				
			},
			//处理接收到的数据
			async processingData(data) {
				console.log('处理接收到的数据',data);
				let result = JSON.parse(data.slice(0, data.length - 1))
				//显示日志在子窗口
				that.showLogSubwindow('处理接收到的数据'+data)
				//判断当前指令是否已经执行过，已经执行过就跳过
				let resData=await that.isExecuted(result)
				if(resData==0){//已经执行过当前命令了，无需重复回复
					console.log('已经执行过当前命令了，无需重复回复');
					return
				}
				if (result.CommondNo == 1) { //获取设备uuid
					receivedStr = ''
					that.seal.UUID = result.UUID
					//判断log日志目录
					that.testingCatalogue()
					//获取服务器印章里面的数据
					that.getSeverSealData()
					return
				}
				if (result.CommondNo == 11) { //按键测试
					receivedStr = ''
					that.KeyTest.checkList.push(result.ExecResult)
					that.KeyTest.checkList = Array.from(new Set(that.KeyTest.checkList))
					if (that.KeyTest.checkList.length == 4) {
						result.ExecResult = that.KeyTest.checkList
						console.log('按键测试',result);
						//处理结果是否人为审核
						that.humanAudit(result)
					}
					return
				}
				if(result.CommondNo==22){//读取rom后是否与配置项ROM匹配，不匹配就失败
					that.read.ROM = result.ExecResult
					if(result.ExecResult!=that.appVersionList.ROM){
						console.log('读取的值与配置项值不匹配');
						that.isSuccessFn(-1, 'noPeople',result.ExecResult)
						return
					}
				}
				if(result.CommondNo==23){
					that.read.APP = result.ExecResult
					if(result.ExecResult!=that.appVersionList.APP){
						console.log('读取的值与配置项值不匹配');
						that.isSuccessFn(-1, 'noPeople',result.ExecResult)
						return
					}
				}
				if(result.CommondNo==36){
					that.read.LET_signal = result.ExecResult
					if(result.ExecResult>that.AppConfig.appVersionList.LTELimit[0]&&result.ExecResult<that.AppConfig.appVersionList.LTELimit[1]){
						
					}else{
						console.log('读取的值与配置项值不匹配');
						that.isSuccessFn(-1, 'noPeople',result.ExecResult)
						return
					}
				}
				if(result.CommondNo==39){
					that.$message.warning('请使用扫码扫描IMEI二维码，进行匹配')
					that.scan.result=result
					setTimeout(()=>{
						console.log(this.$refs.el_input);
						this.$refs.el_input.focus()
					},1000)
					return
				}
				if(result.CommondNo==40){
					that.electricCurrent.result=result
					//串口通信读取电流
					that.serialPortFn()
					return
				}
				// if(result.CommondNo=='24'){
				// 	that.read.WIFI_MAC = result.ExecResult
				// 	that.isSuccessFn(0, 'noPeople',result.ExecResult)
				// 	return
				// }
				if(result.CommondNo==26){
					that.read.IMEI = result.ExecResult
				}
				if(result.CommondNo==27&&result.ExecResult){
					that.read.WIFI_BT = JSON.parse(result.ExecResult)
				}
				if(result.CommondNo==28){
					that.read.Q_Electric = result.ExecResult
				}
				if(result.CommondNo==33){
					that.seal.UUID=result.UUID
				}
				if(result.CommondNo==35){
					that.read.Aging_state = result.ExecResult
				}
				
				if(result.CommondNo==37){
					that.read.ICCID = result.ExecResult
				}
				
				if(result.CommondNo == 3){//如果是拍照
					//上传base64图片
					let reqData={
						appType:that.appType,//当前检测的是哪道工序
						UUID:that.seal.UUID,
						active:'uploadImage',
						base64Str:result.ExecResult
					}
					
					let updataRes=await that.GLOBAL.doPost('https://fc-mp-d469f3c9-30d2-4936-a92e-5888ccb3dd27.next.bspapp.com/http/AddSealData',reqData)
					result.ExecResult=updataRes.data.fileID
					
					//上传成功后删除上个图片
					if(localStorage.getItem('imageFileId-'+that.appType)){
						let reqData2={
							active:'delectImage',
							fileID:localStorage.getItem('imageFileId-'+that.appType)
						}
						let delectRes=await that.GLOBAL.doPost('https://fc-mp-d469f3c9-30d2-4936-a92e-5888ccb3dd27.next.bspapp.com/http/AddSealData',reqData2)
						console.log('删除图片结果',delectRes);
					}
					that.picture={
						showViewer:true,
						src:result.ExecResult,
						showIndex: 0, //点击显示图片第几个
					}
					//存储这次上传成功的fileID，用于下次上传后删除
					localStorage.setItem('imageFileId-'+that.appType,result.ExecResult)
					
				}
				if (result.ExecResult) { //执行成功
					console.log(result.ExecResult);
					//处理结果是否人为审核
					that.humanAudit(result)
				} else {
					//显示日志在子窗口
					that.showLogSubwindow('执行失败')
					//处理结果是否人为审核
					that.humanAudit(result)
				}
			},
			//处理服务器返回的印章检测数据
			async workingProcedure(sealData){
				console.log('获取到服务器的数据',sealData);
				//先检查当前工序之前的工序是否已经检测完毕
				let onoff=await that.beforeCompleted()
				if(!onoff){//说明之前工序未检测完成
					return
				}
				console.log('之前工序是否检测完成',onoff);
				if(sealData){//当前服务器检测过当前工序
					if(sealData.appTypeEnd){
						//设置当前连接状态
						that.stateFn(false)
						that.$message.warning('当前工序已检测完成，请执行下一道工序')
						//当前所有项检测合格才展示二维码
						that.IMEIFn(sealData)
						//全部合格并且在指定工站才能进入用户模式
						that.userTypeFn()
					}else{
						//设置当前连接状态
						that.stateFn(true)
						//处理检测项检测失败或跳过的全部置空
						let arr=that.EmptyFn(JSON.parse(sealData.string))
						console.log(arr);
						//设置菜单哪些已经通过和没通过
						that.setAppMenuList(arr)
					}
				}else{//当前服务器不存在此印章检测数据
					//设置当前连接状态
					that.stateFn(true)
					if(that.appType=='FT6'){
						return
					}
					let arr=JSON.parse(JSON.stringify(that.appMenuList))
					arr.forEach((menuItem)=>{//菜单循环
						menuItem.disabled=false
					})
					//设置菜单哪些已经通过和没通过
					that.setAppMenuList(arr)
				}
				
			},
			//生成IMEI二维码
			IMEIFn(sealData){
				//当前所有项检测合格才展示二维码
				//过滤出IMEI值
				let resultData=JSON.parse(sealData.string).filter((item)=>item.commands[0].CommondNo==26)
				if(resultData&&resultData.length>0){
					that.QRcode.IMEI=resultData[0].commands[0].resultData
					//如果是最后写入数据成功后显示二维码
					that.QRcode.show=true
					setTimeout(()=>{
						//生成IMEI二维码
						that.creatQrCode();
					},1000)
				}
			},
			//全部合格并且在指定工站才能执行的函数
			userTypeFn(){
				//当前工站和进入用户模式工站相等时
				if(that.AppConfig.appType==that.AppConfig.userType){
					//退出产测
					that.sendMsgToTcp('{"CommondNo":21,"CommondName": "结束产测模式","CommondParam": "","CommondTime":""}$')
				}
				//当前工站和指定老化工站相等时
				if(that.AppConfig.appType==that.AppConfig.oldType){
					//进入老化
					that.sendMsgToTcp('{"CommondNo":34,"CommondName": "进入老化状态","CommondParam": "","CommondTime":""}$')
				}
			},
			
			//检测当前工序之前的工序是否检测完成
			async beforeCompleted(){
				if(that.appType=='FT1'){
					return true
				}
				if(that.appType=='FT6'){
					return true
				}
				message=that.$message({
					iconClass: 'el-icon-loading',
					message:'正在检测之前工序是否完成...',
					duration:15000
				})
				let ft1=await that.GLOBAL.doPost('https://fc-mp-d469f3c9-30d2-4936-a92e-5888ccb3dd27.next.bspapp.com/http/AddSealData',{appType:'FT1',UUID:that.seal.UUID,active:'seachSealData'})
				
				//当前工序未检测完成
				if(that.appType=='FT3'){
					console.log('Ft3之前的FT1',ft1)
					message&&message.close()
					if(ft1.data&&ft1.data.data&&ft1.data.data.length>0&&ft1.data.data[0].appTypeEnd){
						return true
					}else{
						that.$message.warning('请先检测第一道工序FT1')
						return false
					}
				}
				let ft3=await that.GLOBAL.doPost('https://fc-mp-d469f3c9-30d2-4936-a92e-5888ccb3dd27.next.bspapp.com/http/AddSealData',{appType:'FT3',UUID:that.seal.UUID,active:'seachSealData'})
				if(that.appType=='FT5'){
					console.log('Ft5之前的FT1',ft1)
					console.log('Ft5之前的FT3',ft3)
					message&&message.close()
					if(ft1.data&&ft1.data.data&&ft1.data.data.length>0&&ft1.data.data[0].appTypeEnd){
						if(ft3.data&&ft3.data.data&&ft3.data.data.length>0&&ft3.data.data[0].appTypeEnd){
							return true
						}else{
							that.$message.warning('请先检测工序FT3')
							return false
						}
					}else{
						that.$message.warning('请先检测工序FT1')
						return false
					}
					
				}
			},
			//处理检测项检测失败或跳过的全部置空
			EmptyFn(data){
				data.forEach((menuItem)=>{//菜单循环
					let onoff=true
					menuItem.commands.forEach(itemcomm=>{
						if(itemcomm.isSuccess==-1||itemcomm.isSuccess==1){
							onoff=false
						}
					})
					menuItem.disabled=onoff
					if(menuItem.disabled==false){
						menuItem.commands.forEach(item=>{
							delete item.isSuccess
							delete item.resultData
						})
					}
				})
				return data
			},
			//检测还有哪些项没有检测过
			isTested(MenuList){
				let arr=MenuList.map((menuItem)=>{
					let onoff=true//默认当前项合格【只有有一个子项不合格，当前项就不合格，需重新检测】
					menuItem.commands.forEach(comItem=>{
						if(comItem.resultData&&comItem.isSuccess==0){
						}else{
							onoff=false
						}
					})
					menuItem.disabled=onoff
					return menuItem
				})
				//判断当前工序是否全部检测成功完毕
				let passArr=arr.filter(item=>item.disabled==false)
				let endResult=false
				if(passArr.length>0){
					endResult=false
				}else{
					endResult=true
				}
				return endResult //true为全部检测成功false就是有没有成功的
			},
			//设置当前连接状态
			stateFn(onoff){
				that.seal.state = onoff
				bus.$emit('homeToMenu', {
					action: 'connect',
					loading:false,
					connect: onoff,
					data:onoff? that.tcp.HOST + ":" + that.tcp.PORT:'点击链接设备'
				})
			},
			//判断当前指令是否已经执行过，已经执行过就跳过
			isExecuted(data){
				return new Promise((result,rejec)=>{
					that.testList.forEach(item=>{
						let arr=item.commands.filter(item2=>item2.CommondNo==data.CommondNo)
						if(arr.length>0){
							if(that.popUp.show&&that.popUp.active.CommondNo==data.CommondNo){
								console.log('当前命令，弹框已存在');
								result(0)//拦截
							}else{
								if(arr[0].isSuccess==0||arr[0].isSuccess==1||arr[0].isSuccess==-1){
									result(0)//拦截
								}else{
									result(-1)
								}
							}
						}
					})
					if(data.CommondNo==1||data.CommondNo==20){//获取设备信息
						result(-1)
					}
					
				})
			},
			//是否需要人为审核
			async humanAudit(result) {
				let active = that.testList[that.ativeTestNum].commands[that.commandIndex]
				//显示日志在子窗口
				that.showLogSubwindow('获取到当前菜单项'+JSON.stringify(active))
				//是否需要人为审核
				if (active.popUp) {
					that.popUp.text=`已发送${active.CommondName}，等待人为审核结果`
					that.popUp.active=active
					let onoff = await that.showOpen()
					//当前执行命令是否成功0成功 -1失败
					that.isSuccessFn(onoff, 'people',result.ExecResult)
				} else { //无需人工审核
					//显示日志在子窗口
					that.showLogSubwindow('无需人工审核')
					receivedStr = ''
					if (result.ExecResult) {
						if(result.ExecResult=='1'){//印章返回1代表失败
							//当前执行命令是否成功
							that.isSuccessFn(-1, 'noPeople',result.ExecResult)
						}else{
							//当前执行命令是否成功
							that.isSuccessFn(0, 'noPeople',result.ExecResult)
						}
					} else {
						that.isSuccessFn(-1, 'noPeople')
					}

				}
			}
		}
	}
</script>
<style scoped="scoped" lang="scss">
	.home {
		height: 100%;
		// 扫码枪
		.codeScanning{
			width: 100%;
		}
		//生成二维码
		.lz-qrcode{
			position: fixed;width: 100%;height: 100%;display: flex;align-items: center;justify-content: center;left: 0;top: 0;z-index: 1000;
			background-color: rgba(0,0,0,0.5);
			.qrcodeWarp{
				display: flex;flex-direction: column;justify-content: center;
				.qrcode{
				    display: inline-block;padding: 10px;background-color: #fff;
				}
				.text{
					text-align: center;color: #fff;margin-top: 10px;
				}
			}
		}
		
		.lz-close-fiexd{
			position: absolute;top: 30px;right: 30px;z-index: 10000000;
		}
		.el-timeline {
			padding: 20px 10px 10px 0;box-sizing: border-box;
			.line-card {
				padding: 15px;

				.card-warp {
					display: flex;
					align-items: center;
					flex-wrap: wrap;
					justify-content: space-between;

					.btn {
						order: 1
					}
					.flex-center{
						flex: 1;
					}
					.card-title {
						font-weight: bold;
						display: flex;
						align-items: center;
						margin-right: 10px;
						justify-content: space-between
					}

					.el-image {
						width: 70px;
						height: 70px;
						border-radius: 4px;
						display: flex;
						align-items: center;
						justify-content: center;
						background-color: #f0f0f0;
					}

					.left {
						flex: 1;
					}
				}

			}
		}

		.li {
			margin-bottom: 10px;

			.li-title {
				width: 100%;
				font-weight: bold;
				padding: 5px 0;
				display: flex;

				.li-t-text {
					color: #20A0FF;
					margin: 0 10px;
				}
			}

			.li-success {
				color: #67c23a;
			}

			.li-fail {
				color: #e6a23c;
			}
		}


	}

	.grid-content {
		margin-bottom: 15px;
	}

	.tip {
		margin-left: 60px
	}

	.flex {
		display: flex;
		margin-right: 200px
	}
</style>
